package com.bearsadmin.service.impl;

import com.bearsadmin.common.BusinessException;
import com.bearsadmin.config.FileUploadConfig;
import com.bearsadmin.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 文件服务实现类
 *
 * @author Bears Admin
 * @since 1.0.0
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    /**
     * 允许上传的图片格式
     */
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "webp");

    /**
     * 最大文件大小 (10MB)
     */
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    @Override
    public String uploadAvatar(MultipartFile file, Long userId) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException("请选择要上传的文件");
        }

        // 验证文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new BusinessException("文件大小不能超过10MB");
        }

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        if (!StringUtils.hasText(originalFilename)) {
            throw new BusinessException("文件名不能为空");
        }

        // 获取文件扩展名
        String extension = getFileExtension(originalFilename).toLowerCase();
        if (!ALLOWED_EXTENSIONS.contains(extension)) {
            throw new BusinessException("只支持上传 " + String.join(", ", ALLOWED_EXTENSIONS) + " 格式的图片");
        }

        try {
            // 创建上传目录
            File uploadDir = new File(FileUploadConfig.AVATAR_PATH);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 生成新文件名：用户ID_时间戳_随机UUID.扩展名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String randomId = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
            String newFilename = String.format("%d_%s_%s.%s", userId, timestamp, randomId, extension);

            // 保存文件
            File targetFile = new File(uploadDir, newFilename);
            file.transferTo(targetFile);

            // 返回文件访问URL
            String fileUrl = "/uploads/avatars/" + newFilename;
            log.info("用户 {} 头像上传成功: {}", userId, fileUrl);

            return fileUrl;

        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new BusinessException("文件上传失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteFile(String filePath) {
        if (!StringUtils.hasText(filePath)) {
            return false;
        }

        try {
            // 从URL路径转换为实际文件路径
            String actualPath;
            if (filePath.startsWith("/uploads/")) {
                actualPath = FileUploadConfig.UPLOAD_PATH + filePath.substring("/uploads/".length());
            } else {
                actualPath = filePath;
            }

            File file = new File(actualPath);
            if (file.exists() && file.isFile()) {
                boolean deleted = file.delete();
                if (deleted) {
                    log.info("文件删除成功: {}", actualPath);
                } else {
                    log.warn("文件删除失败: {}", actualPath);
                }
                return deleted;
            }
        } catch (Exception e) {
            log.error("删除文件异常: {}", filePath, e);
        }

        return false;
    }

    /**
     * 获取文件扩展名
     *
     * @param filename 文件名
     * @return 扩展名
     */
    private String getFileExtension(String filename) {
        if (!StringUtils.hasText(filename)) {
            return "";
        }
        int lastDotIndex = filename.lastIndexOf('.');
        return (lastDotIndex == -1) ? "" : filename.substring(lastDotIndex + 1);
    }
}